<template>
  <el-dialog title="添加角色" :visible.sync="disVisible" @close="closeForm"
             :close-on-click-modal="true">
    <el-form :model="role" :rules="rules" ref="addForm" label-width="100px">
      <el-form-item label="角色名称" prop="name">
        <el-input v-model="role.name" clearable></el-input>
      </el-form-item>
      <el-form-item label="角色code" prop="code">
        <el-input v-model="role.code" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">添加</el-button>
        <el-button @click="closeForm">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>

export default {
  name: "AddRole",
  props: {
    formVisible: Boolean
  },
  data() {
    return {
      disVisible: this.formVisible,
      role: {
        name: '',
        code: ''
      },
      rules: {
        name: [{required: true, message: '请输入角色名称', trigger: 'blur'}],
        code: [{required: true, message: '请输入角色code', trigger: 'blur'}]
      }
    };
  },
  methods: {
    submitForm() {
      this.$refs.addForm.validate(isValid => {
        if (!isValid) {
          this.$message({
            message: "请正确填写表单",
            type: "error",
            duration: 2000
          })
          return;
        }
        this.$axios.postForm("/role/addRole", this.role).then(response => {
          let responseData = response.data;
          if (responseData.code == 200) {
            this.$message({
              message: "添加成功",
              type: "success",
              duration: 2000
            })
            this.$refs.addForm.resetFields();
            this.disVisible = false;
            this.$emit('roleList');
          }else {
            this.$message({
              message:responseData.msg,
              type:"error",
              duration:2000
            })
            return;
          }
        })
      })
    },
    closeForm() {
      this.$refs.addForm.resetFields();
      this.$emit('update:addFormVisible', false)
    }
  },
  watch: {
    formVisible(newVal) {
      this.disVisible = newVal;
    }
  }
}
</script>

<style scoped>

</style>